package com.yuyou.fn.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.wens.mybatisplus.plugins.Page;
import com.google.common.collect.Collections2;
import com.yuyou.fn.common.constant.ClassLevelEnum;
import com.yuyou.fn.common.constant.YesNoEnum;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.*;
import com.yuyou.fn.crm.constant.PriorityEnum;
import com.yuyou.fn.crm.constant.RegPossibleEnum;
import com.yuyou.fn.crm.constant.VisitWayEnum;
import com.yuyou.fn.crm.entity.*;
import com.yuyou.fn.crm.service.*;
import com.yuyou.fn.crm.vo.*;
import com.yuyou.fn.educational.entity.BaseGrade;
import com.yuyou.fn.educational.entity.Campus;
import com.yuyou.fn.educational.entity.Teacher;
import com.yuyou.fn.educational.service.IBaseGradeService;
import com.yuyou.fn.educational.service.ICampusService;
import com.yuyou.fn.educational.service.ITeacherService;
import com.yuyou.fn.educational.vo.TeacherQueryVo;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.platform.vo.SysUserQueryVo;
import com.yuyou.fn.report.vo.StudentRegDetailQueryVo;
import com.yuyou.fn.util.Excels;
import com.yuyou.fn.util.Webs;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.result.ExcelImportResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by wens on 2018/02/05.
 */
@Controller
@RequestMapping("/api/admin/crm")
public class AdminCrmController extends ApiBaseController {

    @Resource
    private IBaseGradeService baseGradeService;

    @Resource
    private ICampusService campusService;

    @Resource
    private IFromCategoryService fromCategoryService;

    @Resource
    private IMarketImportService marketImportService;

    @Resource
    private ICustomerResourceService customerResourceService;

    @Resource
    private IWorkSetupTemplateService workSetupTemplateService;

    @Resource
    private IWorkSetupOfCampusService workSetupOfCampusService;

    @Resource
    private ITeacherService teacherService;

    @Resource
    private IVisitService visitService ;

    @Resource
    private IVisitDetailService visitDetailService ;

    @Resource
    private ICrmDepartmentService crmDepartmentService;

    @Resource
    private ICrmUserDepartmentService crmUserDepartmentService;



    @ApiOperation("用户部门列表")
    @RequestMapping(value = "/userDepartmentList" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<CrmUserDepartmentDetailVo>> userDepartmentList(@ModelAttribute SysUserQueryVo sysUserQueryVo, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo , @RequestParam(value = "pageSize", defaultValue = "20") int pageSize ) throws IOException {
        Page<CrmUserDepartmentDetailVo> page=crmUserDepartmentService.findUserDepartmentDetailPage(sysUserQueryVo,pageNo,pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("单个用户部门")
    @RequestMapping(value = "/userDepartment" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<CrmUserDepartment> userDepartment(@RequestParam("userId")long userId ) throws IOException {
        CrmUserDepartment crmUserDepartment=crmUserDepartmentService.findUserDepartByUserId(userId);
        return ReturnResult.success(crmUserDepartment);
    }

    @ApiOperation("保存或者更新用户部门")
    @RequestMapping(value = "/saveOrUpdateUserDepartment" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<MarketImport>> saveOrUpdateUserDepartment(@ModelAttribute CrmUserDepartSaveUpdateVo crmUserDepartSaveUpdateVo) throws IOException {
        crmUserDepartmentService.saveOrUpdateUserDepart(crmUserDepartSaveUpdateVo);
        return ReturnResult.success("ok");
    }



    @ApiOperation("下载导入模板")
    @RequestMapping(value = "/downloadImportTemplate" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void downloadImportTemplate(@RequestParam(value = "areaTeamId")Long areaTeamId , HttpServletRequest request, HttpServletResponse response ) throws IOException {
        String[] titles  = new String[]{"学生姓名","性别","年级","来源大类","来源小类","意向校区","电话号码","项目活动名称","项目活动日期","紧急程度","备注","回收时长(天)"};
        Webs.writeExcel(request,response,this.resourceImportTemplate(areaTeamId,titles),"客户资源导入模板");
        return ;
    }

    private XSSFWorkbook resourceImportTemplate(long areaTeamId,String[] titles){
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("客户资源");
        XSSFRow firstRow = sheet.createRow(0);


        List<FromCategory> fromCategories = fromCategoryService.findAllFromCategoryByAreaTeamId(areaTeamId);

        if(fromCategories == null || fromCategories.isEmpty() ){
            firstRow.createCell(0).setCellValue("这个区域来源类别未设置,无法下载模板");
            return workbook;

        }

        List<BaseGrade> grades = baseGradeService.findAllFromCache();
        List<String> gradeName = BeanUtils.toList(grades,"gradeName") ;
        Excels.createDict(workbook,"年级",gradeName );

        Map<Long, List<FromCategory>> parentCategoryId2FromCategory = BeanUtils.toGroup(fromCategories, "parentCategoryId");
        List<FromCategory> rootFromCategories = parentCategoryId2FromCategory.get(0l);
        List<String> categoryNames = BeanUtils.toList(rootFromCategories, "categoryName");
        Excels.createDict(workbook,"来源大类",categoryNames);

        for(FromCategory fromCategory : rootFromCategories ){
            List<FromCategory> subs = parentCategoryId2FromCategory.get(fromCategory.getCategoryId());
            if(subs == null  ){
                subs = Collections.EMPTY_LIST ;
            }
            List<String> subCategoryNames = BeanUtils.toList(subs, "categoryName");
            Excels.createDict(workbook,fromCategory.getCategoryName() ,subCategoryNames);
        }


        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }

        List<Campus> campus = campusService.findCampusByAreaTeamId(areaTeamId);
        List<String> campusNames = BeanUtils.toList(campus, "campusName");
        Excels.createDict(workbook,"校区" ,campusNames);
        Excels.createDict(workbook,"性别" , Arrays.asList("男","女"));
        Excels.createDict(workbook,"紧急程度" , Arrays.asList("低","中","高"));
        Excels.addFormulaListConstraint(sheet, "性别", 1 , 1024 * 5  , 1, 1);
        Excels.addFormulaListConstraint(sheet, "年级", 1 , 1024 * 5  , 2, 2);
        Excels.addFormulaListConstraint(sheet, "来源大类", 1 , 1024 * 5  , 3, 3 );
        Excels.addFormulaListConstraint(sheet, "校区", 1 , 1024 * 5  , 5, 5 );
        Excels.addFormulaListConstraint(sheet, "紧急程度", 1 , 1024 * 5  , 9, 9 );
        XSSFCellStyle dateStyle = workbook.createCellStyle();
        XSSFDataFormat dataFormat = workbook.createDataFormat();
        dateStyle.setDataFormat(dataFormat.getFormat("yyyy-mm-dd"));


        for(int i = 1 ; i < 1024 * 5 ; i++ ){
            Excels.addFormulaListConstraint(sheet, String.format("INDIRECT(D%d)" , (i  + 1 )), i , i  , 4, 4 );
        }
        return workbook;
    }


    @ApiOperation("导入客户资源")
    @RequestMapping(value = "/importCustomerResource" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> importCustomerResource(@RequestParam(value = "areaTeamId")Long areaTeamId, MultipartFile file ,HttpServletRequest request) throws Exception {
        SysUser sysUser=this.getUser(request);
        CrmUserDepartment crmUserDepartment=crmUserDepartmentService.findUserDepartByUserId(sysUser.getUserId());

        if (crmUserDepartment==null){
            throw new BusException("该账号尚未设置部门，无法导入");
        }
        if(file == null ){
            throw new BusException("请上传文件") ;
        }
        Long departmentId=crmUserDepartment.getDepartmentId();
        String fileName = file.getName().toLowerCase();

        if(fileName.endsWith(".xlsx")){
            throw new BusException("请上传excel文件") ;
        }

        InputStream inputStream = file.getInputStream();
        ImportParams params = new ImportParams();
        params.setNeedVerfiy(true);

        ExcelImportResult<ImportCustomerResourceVo> importResult = ExcelImportUtil.importExcelVerify(inputStream, ImportCustomerResourceVo.class, params);
        List<ImportCustomerResourceVo> importCustomerResourceVos = importResult.getList();
        if(importResult.isVerfiyFail()){
            StringBuilder sb  = new StringBuilder();
            for(int i = 0 ; i < importCustomerResourceVos.size() ;i++ ){
                ImportCustomerResourceVo importCustomerResourceVo = importCustomerResourceVos.get(i);
                if(StringUtils.isNoneEmpty(importCustomerResourceVo.getErrorMsg())){
                    if(sb.length() != 0 ){
                        sb.append(",");
                    }
                    sb.append("【第").append( i+ 2 ).append("行】").append(importCustomerResourceVo.getErrorMsg());
                }
            }
            return ReturnResult.fail(sb.toString());
        }
        marketImportService.importCustomerResource(areaTeamId,departmentId,importCustomerResourceVos, Principals.get() );
        return ReturnResult.success("OK");
    }


    @ApiOperation("导入纪录")
    @RequestMapping(value = "/importRecord" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<MarketImport>> importRecord(MarketImportQueryVo query, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo , @RequestParam(value = "pageSize", defaultValue = "20") int pageSize ) throws IOException {
        Page<MarketImport> page = marketImportService.findMarketImportByQuery(query,pageNo,pageSize );
        return ReturnResult.success(page);
    }

    @ApiOperation("导入明细")
    @RequestMapping(value = "/importDetail" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<CustomerResource>> importDetail(@RequestParam("marketImportId") Long marketImportId) throws IOException {
        List<CustomerResource> customerResources = marketImportService.findImportDetailByMarketImportId(marketImportId);
        return ReturnResult.success(customerResources);
    }


    @ApiOperation("来源大类列表")
    @RequestMapping(value = "/bigFromCategory" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<FromCategory>> bigFromCategory(@RequestParam(value = "areaTeamId")Long areaTeamId ) throws IOException {
        List<FromCategory> roots = fromCategoryService.findRootFromCategoryByAreaTeamId(areaTeamId);
        return ReturnResult.success(roots);
    }

    @ApiOperation("删除来源大类")
    @RequestMapping(value = "/delBigFromCategory" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<FromCategory>> delBigFromCategory(@RequestParam(value = "categoryId")Long categoryId ) throws IOException {
        fromCategoryService.delBigFromCategory(categoryId);
        return ReturnResult.success("OK");
    }

    @ApiOperation("来源小类列表")
    @RequestMapping(value = "/smallFromCategory" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<FromCategory>> smallFromCategory(@RequestParam(value = "bigFromCategory")Long bigFromCategory ) throws IOException {
        List<FromCategory> categories = fromCategoryService.findSubFromCategoryByRootFromCategoryId(bigFromCategory);
        return ReturnResult.success(categories);
    }

    @ApiOperation("创建来源大类")
    @RequestMapping(value = "/saveOrUpdateBigFromCategory" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveOrUpdateBigFromCategory( @RequestParam(value = "categoryId" ,required = false) Long categoryId , @RequestParam(value = "areaTeamId")Long areaTeamId,@RequestParam("categoryName") String categoryName ) throws IOException {
        fromCategoryService.saveOrUpdateBigFromCategory(categoryId,areaTeamId,categoryName);
        return ReturnResult.success("OK");
    }

    @ApiOperation("创建来源小类")
    @RequestMapping(value = "/saveOrUpdateSmallFromCategory" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveOrUpdateSmallFromCategory(@RequestParam(value = "parentFromCategoryId")Long parentFromCategoryId,@RequestParam(value = "categoryNames[]",required = false ) List<String> categoryNames ) throws IOException {
        fromCategoryService.saveOrUpdateSmallFromCategory(parentFromCategoryId,categoryNames);
        return ReturnResult.success("OK");
    }

    @ApiOperation("保存工作流程设置")
    @RequestMapping(value = "/saveOrUpdateWorkSetupTemplate" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveOrUpdateWorkSetupTemplate(WorkSetupTemplateSaveOrUpdateVo saveOrUpdateVo ) throws IOException {
        workSetupTemplateService.saveOrUpdateWorkSetupTemplate( saveOrUpdateVo ,Principals.get() );
        return ReturnResult.success("OK");
    }

    @ApiOperation("工作流程设置列表")
    @RequestMapping(value = "/workSetupTemplate" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<WorkSetupTemplate>> workSetupTemplate(@RequestParam(value = "areaTeamId" , required = false ) Long areaTeamId , HttpServletRequest request  ) throws IOException {
        List<WorkSetupTemplate> list  = workSetupTemplateService.findWorkSetupTemplateByAreaTeamId( getDataPermission(request) ,areaTeamId );
        return ReturnResult.success(list);
    }

    @ApiOperation("保存校区工作流程设置")
    @RequestMapping(value = "/saveOrUpdateWorkSetupOfCampus" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveOrUpdateWorkSetupOfCampus(WorkSetupOfCampusSaveOrUpdateVo saveOrUpdateVo ) throws IOException {
        workSetupOfCampusService.saveOrUpdateWorkSetupOfCampus(saveOrUpdateVo,Principals.get());
        return ReturnResult.success("OK");
    }

    @ApiOperation("校区工作流程设置列表")
    @RequestMapping(value = "/workSetupOfCampus" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<WorkSetupOfCampus>> workSetupOfCampus(@RequestParam(value = "areaTeamId",required = false ) Long areaTeamId, @RequestParam(value = "campusId",required = false) Long campusId , HttpServletRequest request  ) throws IOException {
        List<WorkSetupOfCampus> list  = workSetupOfCampusService.findWorkSetupOfCampusByAreaTeamId(getDataPermission(request),areaTeamId,campusId );
        return ReturnResult.success(list);
    }

    @ApiOperation("客户资源列表")
    @RequestMapping(value = "/customerResource" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<CustomerResource>> customerResource(CustomerResourceQueryVo queryVo , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo , @RequestParam(value = "pageSize", defaultValue = "20") int pageSize , HttpServletRequest request  ) throws IOException {
        Page<CustomerResource> page = customerResourceService.findCustomerResourceByQuery(getDataPermission(request),queryVo,pageNo,pageSize );
        return ReturnResult.success(page);
    }

    @ApiOperation("资源回收")
    @RequestMapping(value = "/customerResourceRecycle" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<CustomerResource>> customerResourceRecycle(CustomerResourceQueryVo queryVo , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo , @RequestParam(value = "pageSize", defaultValue = "20") int pageSize , HttpServletRequest request  ) throws IOException {
        Page<CustomerResource> page = customerResourceService.findRecycleResourceByQueryByQuery(getDataPermission(request),queryVo,pageNo,pageSize );
        return ReturnResult.success(page);
    }

    @ApiOperation("导出资源回收")
    @RequestMapping(value = "/exportCustomerResourceRecycle" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<CustomerResource>> exportCustomerResourceRecycle(CustomerResourceQueryVo queryVo , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo , @RequestParam(value = "pageSize", defaultValue = "20") int pageSize , HttpServletRequest request,HttpServletResponse response  ) throws IOException {
        Page<CustomerResource> page = customerResourceService.findRecycleResourceByQueryByQuery(getDataPermission(request),queryVo,pageNo,pageSize );
        List<CustomerResource> customerResourceList=page.getRecords();
        /*记录导入次数 ,key=学生姓名、性别、年级、意向校区、电话号码、项目活动名称、项目活动日期*/
        Map<String,Integer> map=new HashMap<>();
        if (customerResourceList!=null){
            Set<String> studentNameSet=new HashSet<>();

            Set<String> phoneSet=new HashSet<>();
            Set<String> projectNameSet=new HashSet<>();

            for (CustomerResource customerResource:customerResourceList){
                studentNameSet.add(customerResource.getStudentName());
                phoneSet.add(customerResource.getPhoneNo());
                projectNameSet.add(customerResource.getProjectName());
            }
            List<CustomerResourceImportNumVo> customerResourceImportNumVoList=customerResourceService.findCustomerResourceImportNum(new ArrayList<>(studentNameSet),new ArrayList<>(phoneSet),new ArrayList<>(projectNameSet));

            if (customerResourceImportNumVoList!=null) {
                for (CustomerResourceImportNumVo customerResourceImportNumVo : customerResourceImportNumVoList) {
                    String key = customerResourceImportNumVo.getStudentName() + "_" + customerResourceImportNumVo.getSex() + "_" + customerResourceImportNumVo.getGradeId() + "_" + customerResourceImportNumVo.getCampusId() + "_" + customerResourceImportNumVo.getPhoneNo() + "_" + customerResourceImportNumVo.getProjectName() + "_" + Utils.formatDate(customerResourceImportNumVo.getProjectTime(), "yyyy-MM-dd");
                    Integer importNum = map.get(key);
                    if (importNum == null) {
                        importNum = 0;

                    }
                    map.put(key, ++importNum);
                }
            }

        }


        String[] titles  = new String[]{"学生姓名","性别","年级","来源大类","来源小类","意向校区","电话号码","项目活动名称","项目活动日期","紧急程度","备注","分配时间","抢占人","导入部门","回收时间","跟进状态","导入次数"};
        XSSFWorkbook workbook = this.resourceImportTemplate(queryVo.getAreaTeamId(), titles);
        XSSFSheet sheet = workbook.getSheet("客户资源");

        int rowNum = 1;

        if (customerResourceList!=null){
            for (CustomerResource customerResource : customerResourceList) {
                String key = customerResource.getStudentName() + "_" + customerResource.getSex() + "_" + customerResource.getGradeId() + "_" + customerResource.getCampusId() + "_" + customerResource.getPhoneNo() + "_" + customerResource.getProjectName() + "_" + Utils.formatDate(customerResource.getProjectTime(), "yyyy-MM-dd");
                Integer importNum = map.get(key);
                int cellNum = 0;

                XSSFRow row = sheet.createRow(rowNum++);
                XSSFCell cell = row.createCell(cellNum++);


                cell.setCellValue(StringUtils.defaultString(customerResource.getStudentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getSex()==null?"":customerResource.getSex()==1?"男":customerResource.getSex()==2?"女":"未设置");

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getGradeName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getBigCategory()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getSmallCategory()));


                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getCampusName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getPhoneNo()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getProjectName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getProjectTime()==null?"":Utils.formatDate(customerResource.getProjectTime(),"yyyy-MM-dd"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getPriority()==null?"":customerResource.getPriority()==0?"低":customerResource.getPriority()==1?"中":"高");

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getRemark()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getAlloCreateTime()==null?"":Utils.formatDate(customerResource.getAlloCreateTime(),"yyyy-MM-dd HH:mm:ss"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getFollowOperatorName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(customerResource.getDepartmentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getRecycleTime()==null?"":Utils.formatDate(customerResource.getRecycleTime(),"yyyy-MM-dd HH:mm:ss"));

                cell = row.createCell(cellNum++);
                cell.setCellValue(customerResource.getVisitStatus()==null?"":customerResource.getVisitStatus()==0?"未跟进":"已跟进");

                cell = row.createCell(cellNum++);
                cell.setCellValue(importNum==null?0:importNum);

            }
        }

        Webs.writeExcel(request, response, workbook,"资源回收");
        return ReturnResult.success("ok");
    }

    @ApiOperation("删除客户资源")
    @RequestMapping(value = "/deleteCustomerResourceByIds" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> deleteCustomerResource(@RequestParam("customerResourceIds") String customerResourceIds, HttpServletRequest request  ) throws IOException {
        customerResourceService.deleteByCustomerResourceIds(Utils.toLongIds(customerResourceIds));
        return ReturnResult.success("ok");
    }


    @ApiOperation("导出资源分配")
    @RequestMapping(value = "/exportCustomerResource", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportCustomerResource(CustomerResourceQueryVo queryVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Webs.writeExcel(request, response, customerResourceService.exportCustomerResource(getDataPermission(request), queryVo), "资源分配");
        return ReturnResult.success("ok");
    }

    @ApiOperation("客户资源列表（潜客）")
    @RequestMapping(value = "/customerResourceForDashboard" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<CustomerResource>> customerResourceForDashboard(CustomerResourceQueryVo queryVo , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo , @RequestParam(value = "pageSize", defaultValue = "20") int pageSize , HttpServletRequest request  ) throws IOException {
        Page<CustomerResource> page = customerResourceService.findCustomerResourceByQuery(getDataPermission(request),queryVo,pageNo,pageSize );
        return ReturnResult.success(page);
    }

    @ApiOperation("我的客户资源列表")
    @RequestMapping(value = "/myCustomerResource" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<CustomerResource>> myCustomerResource(CustomerResourceQueryVo queryVo , @RequestParam(value = "pageNo", defaultValue = "1") int pageNo , @RequestParam(value = "pageSize", defaultValue = "20") int pageSize , HttpServletRequest request  ) throws IOException {
        queryVo.setFollowOperatorId(Principals.get().id);
        Page<CustomerResource> page = customerResourceService.findCanVisitCustomerResourceByQuery(getDataPermission(request),queryVo,pageNo,pageSize );
        return ReturnResult.success(page);
    }

    @ApiOperation("抢占客户资源")
    @RequestMapping(value = "/takeCustomerResource" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> takeCustomerResource(@RequestParam("customerResourceId") Long customerResourceId ) throws IOException {
        boolean b = customerResourceService.takeCustomerResource(customerResourceId, Principals.get());
        if(!b){
            return ReturnResult.success("Fail");
        }
        return ReturnResult.success("OK");
    }

    @ApiOperation("分配校区")
    @RequestMapping(value = "/alloCampus" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> alloCampus(@RequestParam("customerResourceId[]") List<Long> customerResourceIds ,@RequestParam("campusId") Long campusId  ) throws IOException {
        boolean b = customerResourceService.alloCampus(customerResourceIds, campusId , Principals.get());
        if(!b){
            return ReturnResult.fail("Fail");
        }
        return ReturnResult.success("OK");
    }

    @ApiOperation("分配跟进人")
    @RequestMapping(value = "/alloFollow" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> alloFollow(@RequestParam("customerResourceId[]") List<Long> customerResourceIds , @RequestParam(value = "followId",required = false ) Long followId ) throws IOException {
        boolean b = customerResourceService.alloFollow(customerResourceIds , followId, Principals.get());
        if(!b){
            return ReturnResult.fail("Fail");
        }
        return ReturnResult.success("OK");
    }

    @ApiOperation("抢占人")
    @RequestMapping(value = "/follows" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<FollowVo>> follows(@RequestParam("busTeamId") Long busTeamId ) throws IOException {
        TeacherQueryVo teacherQueryVo = new TeacherQueryVo();
        teacherQueryVo.setBusTeamId(busTeamId);
        teacherQueryVo.setAccessType(1);
        teacherQueryVo.setStatus(1);
        List<Teacher> teachers = teacherService.findTeacherByQueryForList(teacherQueryVo);
        Collection<FollowVo> followVos = Collections2.transform(teachers, input -> new FollowVo( input.getTeacherId(),input.getTeacherName() ));
        return ReturnResult.success(followVos);
    }

    @ApiOperation("添加回访记录")
    @RequestMapping(value = "/saveVisitContent" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> saveVisitContent(VisitSaveVo visitSaveVo , @RequestParam(name = "visitTime") String visitTime ) throws IOException {
        visitSaveVo.setVisitTime(TimeUtils.parse(visitTime,"yyyy-MM-dd HH:mm:ss"));
        visitService.saveVisit(visitSaveVo,Principals.get());
        return ReturnResult.success("OK");
    }

    @ApiOperation("单条资源回访记录列表")
    @RequestMapping(value = "/findOneResourceVisitList" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult< List<Visit>> findOneResourceVisitList(@RequestParam("customerResourceId")long customerResourceId) throws IOException {
        List<Visit> visitList = visitService.findVisitListByCustomerResourceId(customerResourceId);
        return ReturnResult.success(visitList);
    }


    @ApiOperation("回访记录列表")
    @RequestMapping(value = "/visitDetail" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<VisitDetail>> visitDetail(@ModelAttribute VisitDetailQueryVo queryVo,@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,@RequestParam(value = "pageSize", defaultValue = "20") int pageSize , HttpServletRequest request ) throws IOException {
        Page<VisitDetail> page = visitDetailService.findVisitDetailByQuery(getDataPermission(request), queryVo,pageNo ,pageSize) ;
        return ReturnResult.success(page);
    }

    @ApiOperation("我的回访记录列表")
    @RequestMapping(value = "/myVisitDetail" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<VisitDetail>> myVisitDetail(@ModelAttribute VisitDetailQueryVo queryVo,@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,@RequestParam(value = "pageSize", defaultValue = "20") int pageSize , HttpServletRequest request ) throws IOException {
        Principals.Principal principal=Principals.get();
        if (principal==null){
            throw new BusException("请登录");
        }
        queryVo.setFollowOperatorId(principal.id);
        Page<VisitDetail> page = visitDetailService.findVisitDetailByQuery(getDataPermission(request), queryVo,pageNo ,pageSize) ;
        return ReturnResult.success(page);
    }



    @ApiOperation("导出回访记录")
    @RequestMapping(value = "/exportVisitDetail" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void exportVisitDetail2(@ModelAttribute VisitDetailQueryVo queryVo, HttpServletRequest request , HttpServletResponse response ) throws IOException {

        Webs.writeExcel(request,response,visitDetailService.exportVisitDetail2Excel(getDataPermission(request) , queryVo),"回访记录");
    }

    @ApiOperation("导出我的回访记录")
    @RequestMapping(value = "/exportMyVisitDetail" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void exportMyVisitDetail2(@ModelAttribute VisitDetailQueryVo queryVo, HttpServletRequest request , HttpServletResponse response ) throws IOException {
        Principals.Principal principal=Principals.get();
        if (principal==null){
            throw new BusException("请登录");
        }
        queryVo.setFollowOperatorId(principal.id);
        Webs.writeExcel(request,response,visitDetailService.exportVisitDetail2Excel(getDataPermission(request) , queryVo),"回访记录");
    }


    @ApiOperation("资源分析列表")
    @RequestMapping(value = "/analyzeCustomerResource" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<VisitDetail>> analyzeCustomerResource(CustomerResourceQueryVo queryVo,HttpServletRequest request) throws IOException {
        List<AnalyzeStatResultOfCustomerResourceVo> results = customerResourceService.analyzeCustomerResource(getDataPermission(request), queryVo);
        return ReturnResult.success(results);
    }



    @ApiOperation("导出资源分析")
    @RequestMapping(value = "/exportAnalyzeCustomerResource" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void exportAnalyzeCustomerResource(CustomerResourceQueryVo queryVo,HttpServletRequest request,HttpServletResponse response ) throws IOException {

        List<AnalyzeStatResultOfCustomerResourceVo> results = customerResourceService.analyzeCustomerResource(getDataPermission(request), queryVo);

        SXSSFWorkbook workbook = new SXSSFWorkbook();
        SXSSFSheet sheet = workbook.createSheet("资源分析");

        String[] titles  = new String[]{"区域","校区","项目名称","分配时间区间","项目活动日期","来源大类","来源小类","分配资源数量","准时跟进数量","超时数量","未跟进数量","及时跟进率","成交人数","成交科数","成交金额","成交学生占资源比例"} ;
        SXSSFRow firstRow = sheet.createRow(0);
        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }

        int rowIndex  = 1 ;
        for(AnalyzeStatResultOfCustomerResourceVo result  : results ){
            SXSSFRow row = sheet.createRow(rowIndex++);

            int c = 0;
            SXSSFCell cell = row.createCell(c++);
            cell.setCellValue(result.getAreaTeamName());

            cell = row.createCell(c++);
            cell.setCellValue(result.getCampusName());

            cell = row.createCell(c++);
            cell.setCellValue(result.getProjectName());

            cell =row.createCell(c++);
            cell.setCellValue(Utils.formatDate(queryVo.getAlloCreateTimeOfStart(),"yyyy-MM-dd")+" - "+Utils.formatDate(queryVo.getAlloCreateTimeOfEnd(),"yyyy-MM-dd"));

            cell = row.createCell(c++);
            cell.setCellValue(result.getProjectTime());

            cell = row.createCell(c++);
            cell.setCellValue(result.getBigCategory());

            cell = row.createCell(c++);
            cell.setCellValue(result.getSmallCategory());

            cell = row.createCell(c++);
            cell.setCellValue(result.getStudentAmount());

            cell = row.createCell(c++);
            cell.setCellValue(result.getOntimeAmount());


            cell = row.createCell(c++);
            cell.setCellValue(result.getTimeoutAmount());

            cell = row.createCell(c++);
            cell.setCellValue(result.getNotVisitAmount());

            cell = row.createCell(c++);
            cell.setCellValue(Utils.percent( result.getOntimeAmount(),result.getStudentAmount() ) + "%");


            cell = row.createCell(c++);
            cell.setCellValue(result.getRegStudentAmount());

            cell = row.createCell(c++);
            cell.setCellValue(result.getRegAmount());

            cell = row.createCell(c++);
            cell.setCellValue(BigDecimals.formatBigDecimal(result.getTotalAmount(),"0.00"));

            cell = row.createCell(c++);
            cell.setCellValue(Utils.percent( result.getRegStudentAmount(),result.getStudentAmount() ) + "%");
        }

        Webs.writeExcel(request,response,workbook,"客户资源分析");
    }


    @ApiOperation("区域部门列表")
    @RequestMapping(value = "/findDepartmentList" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<CrmDepartment> > findDepartmentList(@RequestParam("areaTeamId")long areaTeamId,HttpServletRequest request) throws IOException {
        List<CrmDepartment> crmDepartmentList=crmDepartmentService.findDepartmentListByAreaTeamId(areaTeamId);
        return ReturnResult.success(crmDepartmentList);
    }

    @ApiOperation("更新区域部门")
    @RequestMapping(value = "/saveOrUpdateDepartment" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<VisitDetail>> saveOrUpdateDepartment(@RequestParam("areaTeamId")long areaTeamId,@RequestParam("departmentJson")String departmentJson, HttpServletRequest request) throws IOException {
        List<CrmDepartmentVo> crmDepartmentVoList= JSONObject.parseArray(departmentJson,CrmDepartmentVo.class);
        crmDepartmentService.saveOrUpdateCrmDepartment(areaTeamId,crmDepartmentVoList);
        return ReturnResult.success("ok");
    }


    @ApiOperation("资源明细")
    @RequestMapping(value = "/analyzeStudentOfCustomerResource" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<AnalyzeStudentOfCustomerResourceVo>> analyzeStudentOfCustomerResource(CustomerResourceQueryVo queryVo,StudentRegDetailQueryVo studentRegDetailQueryVo,@RequestParam("pageNo")int pageNo,@RequestParam("pageSize")int pageSize, HttpServletRequest request) throws IOException {
        Page<AnalyzeStudentOfCustomerResourceVo> analyzeStudentOfCustomerResourceVoPage = customerResourceService.analyzeStudentOfCustomerResource(getDataPermission(request), queryVo, studentRegDetailQueryVo, pageNo, pageSize);
        return ReturnResult.success(analyzeStudentOfCustomerResourceVoPage);
    }


    @ApiOperation("导出资源明细")
    @RequestMapping(value = "/exportAnalyzeStudentOfCustomerResource", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportAnalyzeStudentOfCustomerResource(CustomerResourceQueryVo queryVo, StudentRegDetailQueryVo studentRegDetailQueryVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Webs.writeExcel(request, response, customerResourceService.exportAnalyzeStudentOfCustomerResource(getDataPermission(request), queryVo,studentRegDetailQueryVo), "资源明细");
        return ReturnResult.success("ok");
    }


    @ApiOperation("首次转化统计")
    @RequestMapping(value = "/firstRegOfCustomerResource" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<CustomerResource>> firstRegOfCustomerResource(@ModelAttribute CustomerResourceQueryVo queryVo,@RequestParam("pageNo")int pageNo,@RequestParam("pageSize")int pageSize, HttpServletRequest request) throws IOException {
        Page<CustomerResource> customerResourcePage = customerResourceService.findCustomerResourceByQuery(getDataPermission(request), queryVo, pageNo, pageSize);
        return ReturnResult.success(customerResourcePage);
    }


    @ApiOperation("导出首次转化统计")
    @RequestMapping(value = "/exportFirstRegOfCustomerResource", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportFirstRegOfCustomerResource(CustomerResourceQueryVo queryVo,  HttpServletRequest request, HttpServletResponse response) throws IOException {
        Webs.writeExcel(request, response, customerResourceService.exportFirstRegOfCustomerResource(getDataPermission(request), queryVo), "首次转化统计");
        return ReturnResult.success("ok");
    }

    @ApiOperation("获取来源大类来源小类")
    @RequestMapping(value = "/findFromCategoryList" ,method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult< List<FromCategoryRelativeVo>> findFromCategoryList(@RequestParam("areaTeamId")long areaTeamId,HttpServletRequest request) throws IOException {
        List<FromCategoryRelativeVo> fromCategoryRelative = fromCategoryService.findFromCategoryRelative(areaTeamId);
        return ReturnResult.success(fromCategoryRelative);
    }











}
